import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 
 * 
 * @author io.porges
 *
 */
public class BTClient {

	public static void main(String[] args) {
		String torrentName, fileName;

		if (args.length != 2) {
			try {
				BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
				System.out.print("Enter .torrent filename: ");
				torrentName = in.readLine();
				System.out.print("Enter output filename: ");
				fileName = in.readLine();
			} catch (IOException e) {
				System.out.println("IO error...exiting");
				System.exit(1);
				return;
			}
		} else {
			torrentName = args[0];
			fileName = args[1];
		}

		TorrentFileHandler torrentFileHandler = new TorrentFileHandler();
		GlobalTorrentInfo info = new GlobalTorrentInfo ();

		info.torrentFile = torrentFileHandler.openTorrentFile(torrentName);
		info.tracker = new TrackerInterface(info.torrentFile, info);
		info.dataFileHandler = new FileHandler2 (torrentName, fileName, info.torrentFile, info);
		info.peers = new PeersInterface(info);
		info.acceptor = null;

		startBTClient(info);

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input = null;
		try {
			while (true) {
				input = br.readLine(); //blocks if no input
				handleCommand(input, info);
			}
		} catch (IOException ioe) {
			System.out.println("Error trying to read command line input.");
			System.exit(1);
		}

	}

	private static void startBTClient(GlobalTorrentInfo info) {
		if (info.isRunning) {
			System.out.println("torrent already running");
		} else
			info.isRunning = true;
		try {
			info.acceptor = PeerConnectionAcceptor.beginAccepting(info);
		} catch (IOException e) {
			System.out.println("Could not create a peer connection acceptor in BTClient. Exiting");
			System.exit(1);
		}
		info.tracker.startTracker();	//this starts the peer monitor
		info.peers.startPeerMonitor();
	}

	/**
	 * Handles start/stop/pause/etc.
	 * May change the value of running to false to exit.
	 * May call functions in fileHandler to pause, resume, etc...
	 * 
	 */
	public static void handleCommand(String input, GlobalTorrentInfo info){
		if (input.equals("start")){
			startBTClient(info);
		}
		else if (input.equals("pause")){
			info.tracker.stopTracker();
			info.peers.stopPeers();
			info.peers.killAllConnectedPeers();
			info.acceptor.stopAccepting();
		}
		else if (input.equals("resume")){
			startBTClient(info);
		}
		else if (input.equals("stop")) {
			info.tracker.stopTracker();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			System.exit(0);
		}
	}








}
